package com.slipper.system.codeless.controller;

import com.slipper.constants.Constants;
import com.slipper.core.gson.GsonUtil;
import com.slipper.system.codeless.bo.InterfaceFolderBO;
import com.slipper.system.codeless.bo.InterfaceBO;
import com.slipper.system.codeless.service.InterfaceFolderService;
import com.slipper.system.codeless.service.InterfaceService;
import com.slipper.system.codeless.vo.InterfaceVO;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 接口信息表
 */
@RestController
@RequestMapping("/system/interface")
public class InterfaceController {
    private static final Logger logger = LoggerFactory.getLogger(InterfaceController.class);

    @Resource
    private InterfaceFolderService interfaceFolderService;
    @Resource
    private InterfaceService interfaceService;

    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody InterfaceBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(interfaceService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody InterfaceBO bo) {
        return ResultUtil.successResult(interfaceService.queryList(bo));
    }

    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody InterfaceBO bo) {
        return ResultUtil.successResult(interfaceService.queryPage(bo));
    }

    @PostMapping("/queryTree")
    public String queryTree() {
        List<InterfaceFolderBO> folderList = interfaceFolderService.queryList(new InterfaceFolderBO());
        TreeInfo folderTreeInfo = new TreeInfo("接口");
        folderTreeInfo.setRootId(Constants.ROOT_ID);
        folderTreeInfo.setIdField("id");
        folderTreeInfo.setPidField("parentId");
        folderTreeInfo.setTextField("name");
        folderTreeInfo.setNodeType("folder");
        folderTreeInfo.setSortField("ordinal");

        List<InterfaceBO> interfaceList = interfaceService.queryList(new InterfaceBO());
        TreeInfo interfaceTreeInfo = new TreeInfo("");
        interfaceTreeInfo.setIdField("id");
        interfaceTreeInfo.setPidField("folderId");
        interfaceTreeInfo.setTextField("name");
        interfaceTreeInfo.setNodeType("interface");
        interfaceTreeInfo.setSortField("ordinal");

        Node rootNode = TreeUtil.buildTree(
                "asc",
                new Tree(folderTreeInfo, BeanUtil.setOrdinal(folderList)),
                new Tree(interfaceTreeInfo, BeanUtil.setOrdinal(interfaceList, folderList.size())));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody InterfaceBO bo) {
        if (Tool.isBlank(bo.getPath())) {
            return ResultUtil.failureResult("接口路径不能为空！");
        }

        if (interfaceService.existsPath(bo.getId(), bo.getPath())) {
            return ResultUtil.failureResult("接口路径已存在！");
        }

        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(interfaceService.save(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody InterfaceBO bo) {
        return ResultUtil.successResult(interfaceService.delete(bo));
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody Map<String, Object> data) {
        InterfaceVO vo = new InterfaceVO();
        String[] folderIds = (String[]) data.get("folderIds");
        String[] interfaceIds = (String[]) data.get("interfaceIds");
        if (folderIds != null && folderIds.length > 0) {
            InterfaceFolderBO folderQO = new InterfaceFolderBO();
            folderQO.setIds(folderIds);
            vo.setFolderList(interfaceFolderService.queryList(folderQO));
        }
        if (interfaceIds != null && interfaceIds.length > 0) {
            vo.setInterfaceList(interfaceService.queryList(interfaceIds));
        }

        String fileName = "interface-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(InterfaceBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            InterfaceVO vo = GsonUtil.fromJson(AESUtil.decrypt(content), InterfaceVO.class);
            interfaceFolderService.saveList(vo.getFolderList());
            interfaceService.saveList(vo.getInterfaceList());

            return ResultUtil.successResult("导入接口成功。");
        } catch (Exception e) {
            logger.error("文件解释出错！", e);
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
